<?php

namespace App\Livewire\Auth;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\RateLimiter;
use Livewire\Attributes\Validate;
use Livewire\Component;

class Login extends Component
{
    #[Validate('required')]
    public string $account = '';

    #[Validate('required')]
    public string $password = '';

    public function render()
    {
        return view('livewire.auth.login');
    }

    public function submit(Request $request)
    {
        $rate_limiter_key = 'user-login:'.$request->ip();

        $executed = RateLimiter::attempt($rate_limiter_key, 3, fn() => true);

        if (! $executed) {
            $seconds = RateLimiter::availableIn($rate_limiter_key);

            $this->addError('password', __('auth.throttle', compact('seconds')));
            return null;
        }

        if (! Auth::attempt($this->validate(), true)) {
            $this->addError('account', __('auth.failed'));
            return null;
        }

        Auth::logoutOtherDevices($this->password);

        return to_route('home');
    }
}
